function createRouteMap(routes, oldMap) {
  const pathMap = oldMap || Object.create(null);
  routes.forEach((route) => {
    addRouteRecord(pathMap, route);
  });
  return {
    pathMap,
  };
}
// /about/a/b  三个组件  /about {record1}  /about/a {record2} /about/a/b  {record3} 三个组件

// /about/a/b -> 通过匹配到的记录向上查找parent属性将记录维护起来 [record1,record2,record3]

// 用户登录后 才能访问某个页面 这时就可以采用动态路由
function addRouteRecord(pathMap, route, parentRecord) {
  // /about/a 匹配几个组件
  // 可以动态添加路由
  let path = parentRecord
    ? parentRecord.path !== "/"
      ? (parentRecord.path + "/" + route.path)
      : (parentRecord.path + route.path)
    : route.path; // 路径

  let record = {
    // 稍后会添加一些路径
    path,
    component: route.component,
    parent: parentRecord,
    // meta,props,name.....
  };
  if (!pathMap[path]) {
    // 路径相同就过落掉了
    pathMap[path] = record;
  }
  if (route.children) {
    // 当前我的路径的父亲是谁
    route.children.forEach((childRoute) => {
      addRouteRecord(pathMap, childRoute, record);
    });
  }
}
export function createRoute(record,config){
    let matched = [];
    if(record){
        while (record) {
            matched.unshift(record); 
            record = record.parent
        }
    }
    return {
        path:config.path,
        matched
    }
}
export const createMatcher = (routes) => {
  let { pathMap } = createRouteMap(routes); // {path:'/',record:{},path:'/about',record}

  function match(location) {
    // 路径对应的匹配路由是谁 matched:[about,aboutA]  this.$routes.matched
    let record = pathMap[location];
    return createRoute(record,{ // {path:/about/a,matched:[about,aboutA]}
        path:location
    })
     // 稍后会传入路径，我会将对应的记录匹配出来返回
  }
  function addRoutes(routes) {
    // 将新的routes 也增加到pathMap中
    return createRouteMap(routes, pathMap);
  }
  return {
    match,
    addRoutes,
    pathMap,
  };
};
